const actionDb = require('../manageDb/index')
const { T_USER } = require('../config/database')
const { stateConfig } = require('../config/resState')
const { getToken } = require('../token/index');

// 登录
const login = (req, res) => {
	const filter = req.body;
	actionDb(T_USER, filter, 'queryOne').then((result) => {
		if (result) {
			const token = getToken(result._id.toString())
			const { _id,account } = result;
			res.send({
				code: stateConfig.success.code,
				message: '登录成功',
				userInfo: {
					_id,
					account
				},
				token
			})
		} else {
			res.status(stateConfig.parameterError.code).json({ message: "账号或密码错误" })
		}

	}).catch(err => {
		console.log(err)
		res.status(stateConfig.fail.code).json({ message: "操作失败，请联系管理员" })
	})
}
// 注册
const register = async (req, res) => {
	try {
		const filter = req.body;
		const userInfo = await actionDb(T_USER, { account: filter.account }, 'queryOne');
		if (userInfo) {
			res.status(stateConfig.parameterError.code).json({ message: "该账号已被注册" })
			return;
		}
		const result = await actionDb(T_USER, filter, 'addOne');
		res.send({
			code: stateConfig.success.code,
			message: '注册成功',
			data: result
		})
	} catch (error) {
		console.error(error);
		res.status(stateConfig.fail.code).json({ message: error });
	}

}

module.exports = {
	login,
	register
}